<template>
  <div>
        <el-form inline :model="queryForm" style="text-align: left;">
          <el-form-item label="申请日期">
            <el-date-picker
              v-model="queryForm.ordertime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期" 
              :editable="false"
              style="width: 160px"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-radio-group v-model="queryForm.auditStatus">
              <el-radio label="all">全部</el-radio>
              <el-radio label="pending">未审核</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item style="float: right;">
        <!-- 按钮区域 -->
        <el-button-group>
          <el-button type="primary" @click="handleBatch">提交</el-button>
        </el-button-group>
      </el-form-item>
        </el-form>  
        <el-card style="margin-bottom: 20px;">
          <div slot="header" style="padding: 1px 0; height: 5px; line-height: 5px;">
            <span>待提交统计</span>
          </div>
          <el-table :data="summaryTableData" :show-header="false" border size="mini" style="width: 120%">
            <el-table-column label="日期" width="150">
              <template slot-scope="scope">
                <strong>日期:</strong> {{ scope.row.ordertime }}
              </template>
            </el-table-column>
            <el-table-column label="总订餐数量" width="150">
              <template slot-scope="scope">
                <strong>总订餐数量(份):</strong> {{ scope.row.num }}
              </template>
            </el-table-column>
            <el-table-column label="总订餐金额" width="150">
              <template slot-scope="scope">
                <strong>总订餐金额(元):</strong> {{ scope.row.amount }}
              </template>
            </el-table-column>
            <el-table-column label="餐品明细" width="500">
              <template slot-scope="scope">
                <strong>餐品明细数量(份):</strong> {{ scope.row.detail }}
              </template>
            </el-table-column>
          </el-table>
          </el-card>

        <el-table  :data="orderList" tooltip-effect="dark" height="430px" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" width="60">
            <template slot-scope="scope">
              {{ (queryForm.page - 1) * queryForm.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="申请编号" width="100">
            <template slot-scope="scope">{{ scope.row.orderid }}</template>
          </el-table-column>
          <el-table-column label="费用部门" width="80">
            <template slot-scope="scope">{{ scope.row.dname }}</template>
          </el-table-column>
          <el-table-column label="订餐人员" width="150" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.orderpersons }}</template>
          </el-table-column>
          <el-table-column label="订餐类型" width="100">
            <template slot-scope="scope">{{ scope.row.ordertype_name }}</template>
          </el-table-column>
          <el-table-column label="订餐数量" width="80" align="center">
            <template slot-scope="scope">{{ scope.row.num }}</template>
          </el-table-column>
          <el-table-column label="费用金额" width="80" align="center">
            <template slot-scope="scope">¥{{ scope.row.amount }}</template>
          </el-table-column>
          <el-table-column label="当前状态" width="120">
            <template slot-scope="scope">{{ scope.row.state_name }}</template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-button  size="mini"   type="primary"   @click="handleAudit(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px;text-align: right;"
          :page-sizes="[5, 7, 10, 15]"
          :current-page="queryForm.page"
          :page-size="queryForm.limit"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
    <order-detialis  :visible="detailVisible" @refresh-list="getBothTableData" :orderInfo="currentOrder"  :userInfo="userInfo"  @close="detailVisible = false"></order-detialis>
  </div>
</template>

<script>
import OrderDetialis from '@/components/OrderDetialis.vue';
export default {
  components: { OrderDetialis },
    name:'deptsummary',
    data(){
        return{
          userInfo:{
            deptno:'',
            ename:'',
            empno:'',
            dname:'',
            roleid:[]
          },
            orderList:[],
            checkedOrderList:[],
            summaryTableData: [
              {
                ordertime: '',
                num: 0,
                amount: 0,
                detail: '无'
              }
            ],
            queryForm:{
                ordertime:this.getToday(),
                auditStatus: 'all',
                page: 1,
                limit: 7,
                deptno:'',
                state:'',
                minstate:1
            },
            total: 0,
            detailVisible: false,
            currentOrder: {}
        }
    },
    methods:{
      handleSelectionChange(val){
          this.checkedOrderList = val
      },
        getToday() {
            const today = new Date();
            return today.toISOString().split('T')[0];
        },
        getBothTableData(){
          this.getTableData()
          this.getSummaryData()

        },
        getTableData() {
            this.$http.post("/getOrderInfo", this.queryForm).then(res => {
                this.orderList = res.data.data
                this.total = res.data.count
            })
        },
        handleSizeChange(val) {
            this.queryForm.limit = val
            this.getTableData()
        },
        
        handleCurrentChange(val) {
            this.queryForm.page = val
            this.getTableData()
        },
        handleAudit(row) {
          this.$http.get('/getOnes/' + row.id).then(res => {
          this.currentOrder = res.data; 
          this.detailVisible = true;
  });
        },
        setAuditStatus() {
            if (this.queryForm.auditStatus === 'all') {
                this.queryForm.state = '';
                this.queryForm.minstate = 1;
            } else if (this.queryForm.auditStatus === 'pending') {
                if (this.userInfo.roleid.includes(3)) {
                    this.queryForm.state = 1;
                } else if (this.userInfo.roleid.includes(2)) {
                    this.queryForm.state = 2;
                }
                this.queryForm.minstate = '';
            }
        },
        getSummaryData() {
          let querystate = 1;
          if(this.userInfo.roleid.includes(2)){
            querystate = 2
          }
         let params = {
            ordertime: this.queryForm.ordertime,
            deptno: this.queryForm.deptno,
            querystate:querystate

          }
          this.$http.post("/getOrderSummary", params).then(res => {
            console.log(res.data)
            if (res.data && res.data.ordertime) {
              this.summaryTableData = [{
                
                ordertime: res.data.ordertime,
                num: res.data.num || 0,
                amount: res.data.amount || 0,
                detail: res.data.detail || '无'
              }]
            } else {
              
              this.summaryTableData = [{
                ordertime: this.queryForm.ordertime,
                num: 0,
                amount: 0,
                detail: '无'
              }]
            }
          })
        },
        handleBatch(){
          if (this.queryForm.auditStatus === 'all'){
            this.$message.warning("该列表中可能有无需审核订单")
              return 
          }
            if(this.checkedOrderList.length == 0){
              this.$message.warning("请选择要提交的订单")
              return 
            }
              this.$confirm('确定要提交选中订单吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              let orders = []
              for(let order of this.checkedOrderList){
                orders.push(order.id)
              }
              let statelast = 2;
              if(this.userInfo.roleid.includes(2)){
                statelast = 3;
              } 
              let params = {
                orders:orders,
                statelast:statelast
              }

            this.$http.post('/handleBatch', params).then(res => {
              if(res.data === 'success'){
                this.$message.success("提交成功")
                this.getTableData()
                this.getSummaryData()
              } else {
                this.$message.error("提交失败")
              }
            })
          })

        },

    },
    watch: {
        // 监听日期变化，自动筛选
        'queryForm.ordertime': {
            handler(newVal) {
                this.getTableData()
                this.getSummaryData()
            }
        },
        // 监听审核状态变化，自动筛选
        'queryForm.auditStatus': {
            handler(newVal) {
              this.setAuditStatus(); // 先设置状态值
              this.getTableData();
            }
        }
    },
    
    
    created() {
      const roleidStr = localStorage.getItem("roleid") || ''
      this.userInfo.roleid = roleidStr.split(',').map(Number).filter(id=> !isNaN(id))
      this.queryForm.deptno = Number(localStorage.getItem("deptno"))
      this.setAuditStatus();
      this.getTableData()
      this.getSummaryData()
    }

}
</script>

<style>

</style>